package com.example.cim.repository;

import com.example.cim.constant.CIMConstant;
import com.example.cim.model.CIMSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/*
 * 正式场景下，使用redis或者数据库来存储session信息
 */
@Repository
public class SessionRepository {
    @Autowired
    private RedisTemplate<String, CIMSession> redisTemplate;

//    private ConcurrentHashMap<String, CIMSession> map = new ConcurrentHashMap<>();


    public void save(CIMSession session) {
        redisTemplate.opsForValue().set(CIMConstant.USER_SESSION+session.getAccount(), session);
//        map.put(session.getAccount(), session);
    }

    public CIMSession get(String account) {
        CIMSession cimSession = redisTemplate.opsForValue().get(CIMConstant.USER_SESSION+account);
//        return map.get(account);
        return cimSession;
    }

    public void remove(String account) {
        redisTemplate.delete(CIMConstant.USER_SESSION+account);
//        map.remove(account);
    }

    public List<CIMSession> findAll() {
        Set<String> keys = redisTemplate.keys(CIMConstant.USER_SESSION + "*");
        return redisTemplate.opsForValue().multiGet(keys);
    }
}
